package cap.dao.impl;


import cap.bean.Profile;
import cap.dao.ProfileDao;
import cap.db.DBPool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ProfileDaoImpl implements ProfileDao {
	Connection conn=null;
	PreparedStatement ps=null;
	ResultSet rs=null;
	/**
	 *完善个人信息
	 */
	@Override
	public int insertProfile(int userId, String firstName, String lastName, int gender, String telephone) {
		int res = -1;
		try {
			String sql="insert into profile (user_id,first_name,last_name,gender,telephone) values(?, ?, ?, ?, ?)";
			conn=DBPool.getConn();
			ps=conn.prepareStatement(sql);
			ps.setInt(1,userId);
			ps.setString(2,firstName);
			ps.setString(3,lastName);
			ps.setInt(4,gender);
			ps.setString(5,telephone);
			res=ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBPool.close(rs,ps,conn);
		}
		return res;
	}
	/**
	 *根据获取用户信息
	 */
	@Override
	public Profile getByuserId(int userId) {
		Profile pf = null;
		try {
			String sql="select * from profile where user_id=?";
			conn=DBPool.getConn();
			ps=conn.prepareStatement(sql);
			ps.setInt(1,userId);
			rs=ps.executeQuery();
			if (rs.next()) {
				pf = new Profile();
				pf.setId(rs.getInt("id"));
				pf.setUserId(rs.getInt("user_id"));
				pf.setFirstName(rs.getString("first_name"));
				pf.setLastName(rs.getString("last_name"));
				pf.setGender(rs.getInt("gender"));
				pf.setTelephone(rs.getString("telephone"));
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBPool.close(rs,ps,conn);
		}

		return pf;
	}
	/**
	 *修改用户信息
	 */
	@Override
	public int updateProfile(int userId, String firstName, String lastName, int gender, String telephone) {
		int res = -1;
		try {
			String sql="update profile " +
					"set first_name=?, last_name=?, gender=?, telephone=? where user_id=?";
			conn=DBPool.getConn();
			ps=conn.prepareStatement(sql);
			ps.setString(1,firstName);
			ps.setString(2,lastName);
			ps.setInt(3,gender);
			ps.setString(4,telephone);
			ps.setInt(5,userId);
			res=ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBPool.close(rs,ps,conn);
		}
		return res;
	}
}
